<?php
/**
 * Searches our database for posts matching the given criteria
 * @param string $keyword The keyword to search for
 * @param boolean $searchTitle Whether or not to search in the title for the keyword
 * @param boolean $searchContent Whether or not to search in the content for the keyword
 * @param int $afterTime Search for posts made after a certain unix time
 * @param int $beforeTime Search for posts made before a certain unix time
 * @param int $authorID Search for posts by this author id
 * @param string $authorName The author name to search for in the name and username fields, ignored if authorID is specified
 * @param int $eventID Search for posts in this event id
 * @param string $eventName The event name to search for in the name and description fields, ignored if eventID is specified
 * @return boolean|array Returns array of results on success or false on failure (e.g. no parameters given)
 */
function searchPosts($keyword = NULL, $searchTitle = NULL, $searchContent = NULL, 
					$afterTime = NULL, $beforeTime = NULL, 
					$authorID = NULL, $authorName = NULL,
					$eventID = NULL, $eventName = NULL)
{
	$whereQuery = array();
	$connectionToDB = connect();
	
	// Build the query based on the parameters passed
	if($keyword!=NULL && $searchTitle)
	{
		if(strlen($keyword)<=31) // Title is up to 31 characters long
		{
			$whereQuery[] = "`title` LIKE '%" . mysql_real_escape_string($keyword) . "%'";
		}
	}
	
        if($keyword!=NULL && $searchContent)
	{
		$whereQuery[] = "`content` LIKE '%" . mysql_real_escape_string($keyword) . "%'";
	}
	
	if($afterTime!=NULL && $beforeTime!=NULL)
	{
		$whereQuery[] = "`time` >= '" . date("Y-m-d H:i:s", $afterTime) .
						"' AND `time` <= '" . date("Y-m-d H:i:s", $beforeTime) . "'";
	}
	elseif($afterTime!=NULL)
	{
		$whereQuery[] = "`time` >= '" . date("Y-m-d H:i:s", $afterTime) . "'";
	}
	elseif($beforeTime!=NULL)
	{
		$whereQuery[] = "`time` <= '" . date("Y-m-d H:i:s", $beforeTime) . "'";
	}
	
	if($authorID!=NULL) // Author IDs take priority
	{
		$whereQuery[] = "`author` = " . authorID;
	}
	elseif($authorName!=NULL) // Get all ids associated with the given name because ids are unique but names are not, this avoids doing a join
	{
		$authorIDsThatMatchName = mysql_query("SELECT `idusers` FROM `users` 
							WHERE CONCAT_WS(' ',`first_name`,`last_name`) LIKE '%" . mysql_real_escape_string($authorName) . 
							"%' OR `username` LIKE '%" . mysql_real_escape_string($authorName) . "%'");
		if(!$authorIDsThatMatchName)
		{
                    die('Invalid query while searching for author names.');
                }
                
                $authorIDsInArray = array();

                while($row = mysql_fetch_assoc($authorIDsThatMatchName))
                {
                        array_push($authorIDsInArray, $row['idusers']);
                }

                $whereQuery[] = '(' . implode(" OR ", $authorIDsInArray) . ')';
	}
	
	
	if($eventID!=NULL)
	{
		$whereQuery[] = "`events_idevents` = " . eventID;
	}
	elseif($eventName!=NULL) // Get all ids associated with the given name because ids are unique but names are not, this avoids doing a join
	{
		$eventIDsThatMatchName = mysql_query("SELECT `idevent` FROM `events` 
							WHERE `name` LIKE '%" . mysql_real_escape_string($eventName) . 
							"%' OR `description` LIKE '%" . mysql_real_escape_string($eventName) . "%'");
		
                if(!$eventIDsThatMatchName)
		{
                    die('Invalid query while searching through event names.');
                }
                
		$eventIDsInArray = array();
		
		while($row = mysql_fetch_assoc($eventIDsThatMatchName))
		{
			array_push($eventIDsInArray, $row['idevent']);
		}
		
		$whereQuery[] = '(' . implode(" OR ", $eventIDsInArray) . ')';
	}
	
	$combinedWhereQuery = implode(" AND ", $whereQuery);

	// Was the function given at least one valid parameter to build a query with?
	if(!empty($combinedWhereQuery))
	{
            $postSearchResult = mysql_query("SELECT * FROM `posts` WHERE " . $combinedWhereQuery);
            
            $matchingPosts = array();
            
            while($row = mysql_fetch_assoc($postSearchResult))
            {
                array_push($matchingPosts, $row);
            }
            
            mysql_close($connectionToDB);
            return $matchingPosts;
	}
	else // If no parameters were given then do not return anything
	{
            mysql_close($connectionToDB);
            return false;
	}
}

/**
 * Searches our database for events matching the given criteria
 * @param int $eventID Search for events with this id
 * @param string $keyword The keyword to search for
 * @param boolean $searchTitle Whether or not to search in the title for the keyword
 * @param boolean $searchDescription Whether or not to search in the description for the keyword
 * @param int $meetingID Search for events that are part of this meeting id
 * @param string $meetingName The meeting name to search for, ignored if meetingID is specified
 * @param string $serieName The series name to search for, ignored if meetingID is specified
 * @return boolean|array Returns array of results on success or false on failure (e.g. no parameters given)
 */


function searchEvents($eventID = NULL, $keyword = NULL,
        $searchTitle = NULL, $searchDescription = NULL,
        $meetingID = NULL, $meetingName = NULL,
        $serieName = NULL)
{
    
    $whereQuery = array();
    $connectionToDB = connect();
    
    // Build the query based on parameters passed
    if($eventID!=NULL)
    {
        $whereQuery[] = "`idevent` = '" . $eventID . "'";
    }
    elseif($keyword!=NULL && $searchTitle && strlen($keyword)<=31) // Title is up to 31 characters long
    {
		$whereQuery[] = "`name` LIKE '%" . mysql_real_escape_string($keyword) . "%'";
    }
    
    if($keyword!=NULL && $searchDescription && strlen($keyword)<=255) // Description is up to 255 characters long
    {
		$whereQuery[] = "`description` LIKE '%" . mysql_real_escape_string($keyword) . "%'";
    }
    
    if($meetingID!=NULL) // Meeting ID takes priority over names
    {
        $whereQuery[] = "`meetings_idmeetings` = " . $meetingID;
    }
    elseif($meetingName!=NULL && $serieName!=NULL && $meetingName <= 61 && $serieName <= 61) // The names are up to 61 characters long
    {
		$meetingAndSeriesIDsThatMatchName = mysql_query("SELECT `idmeetings` FROM `meetings` 
							WHERE `name` LIKE '%" . mysql_real_escape_string($meetingName) . 
							"%' OR `serie` LIKE '%" . mysql_real_escape_string($serieName) . "%'");
		
		if(!$meetingAndSeriesIDsThatMatchName)
		{
			die('Invalid query while searching through meeting and series names.');
		}
                
		$meetingAndSeriesIDsInArray = array();
		
		while($row = mysql_fetch_assoc($meetingAndSeriesIDsThatMatchName))
		{
			array_push($meetingAndSeriesIDsInArray, $row['idmeetings']);
		}
		
		$whereQuery[] = '(' . implode(" OR ", $meetingAndSeriesIDsInArray) . ')';
    }
    elseif($meetingName!=NULL && $meetingName <= 61) // The names are up to 61 characters long
    {
		$meetingIDsThatMatchName = mysql_query("SELECT `idmeetings` FROM `meetings` 
							WHERE `name` LIKE '%" . mysql_real_escape_string($meetingName) . "%'");
		
		if(!$meetingIDsThatMatchName)
		{
			die('Invalid query while searching through meeting names.');
		}
                
		$meetingIDsInArray = array();
		
		while($row = mysql_fetch_assoc($meetingIDsThatMatchName))
		{
			array_push($meetingIDsInArray, $row['idmeetings']);
		}
		
		$whereQuery[] = '(' . implode(" OR ", $meetingIDsInArray) . ')';
    }
    elseif($serieName!=NULL && $serieName <= 61) // The names are up to 61 characters long
    {
		$serieIDsThatMatchName = mysql_query("SELECT `idmeetings` FROM `meetings` 
							WHERE `serie` LIKE '%" . mysql_real_escape_string($serieName) . "%'");
		
		if(!$serieIDsThatMatchName)
		{
			die('Invalid query while searching through series names.');
		}
                
		$serieIDsInArray = array();
		
		while($row = mysql_fetch_assoc($serieIDsThatMatchName))
		{
			array_push($serieIDsInArray, $row['idmeetings']);
		}
		
		$whereQuery[] = '(' . implode(" OR ", $serieIDsInArray) . ')';
    }
	
	$combinedWhereQuery = implode(" AND ", $whereQuery);
	
	// Was the function given at least one valid parameter to build a query with?
	if(!empty($combinedWhereQuery))
	{
            $eventSearchResult = mysql_query("SELECT * FROM `posts` WHERE " . $combinedWhereQuery);
            
            $matchingEvents = array();
            
            while($row = mysql_fetch_assoc($eventSearchResult))
            {
                array_push($matchingEvents, $row);
            }
            
            mysql_close($connectionToDB);
            return $matchingEvents;
	}
	else // If no parameters were given then do not return anything
	{
            mysql_close($connectionToDB);
            return false;
	}
}
?>
